package com.home_school_platform.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.home_school_platform.result.Result;

import java.util.Calendar;


/**
 * jwt工具类，用于生产jwt,验证jwt,解密jwt
 * @author 卓汉杰
 * */
public class JwtUtils {

    /**
     * 签名加密
     * */
    private static final String SING = "bbBjgjvbhBHBIujbBHBJKBNJKBgvfhcgvfYGVUHJVvjVVGjvh";

    /**
     * 有效时间
     * */
    private static final int day = 7;


    /**
     * 生成token
     * */
    public static String getToken(String userName){

        Calendar instance = Calendar.getInstance();

        //设计过期时间为3天
        instance.add(Calendar.DATE,day);

        String token = JWT.create()
                .withClaim("username", userName)
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));


        return token;

    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

    /**
     *
     * 获取token信息方法
     * */
    public static String getMessage(String token) {
        DecodedJWT verify;


        verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);


        Claim username = verify.getClaims().get("username");
        return username.asString();
    }

    public static void main(String[] args) {
        System.out.println(getMessage("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTE0OTcyNzIsInVzZXJuYW1lIjoiMTkwMzQ1MzAyMTYifQ.juN1BJixxgPisXtTlTRhgyz0bcZnuuo7mMJeXqmC2y4"));
    }

}
